<template>
  <el-card class="box-card">
    <!-- 页面配置部分 -->
    <div>
      <h3>页面配置</h3>
      <el-form :model="form" style="margin-top: 10px; margin-left: 20px;">
        <el-form-item label="图标更换">
          <el-form-item label="" prop="roomImage">
            <image-upload v-model="form.pcIcon"/>
          </el-form-item>
        </el-form-item>
        <el-form-item label="系统名称" style="width: 400px">
          <el-input v-model="form.pcSystem"></el-input>
        </el-form-item>
        <el-form-item label="默认密码" style="width: 400px">
          <el-input
              v-model="form.pcPassword"
              type="password"
              auto-complete="off"
              show-password
          >
          </el-input>
        </el-form-item>
      </el-form>
    </div>

    <!-- 机场设置部分 -->
    <div>
      <h3>机场设置</h3>
      <el-form :model="form" style="margin-top: 10px; margin-left: 20px;">
        <el-form-item label="推流形式" prop="pcStreaming">
          <el-select v-model="form.pcStreaming" placeholder="请选择推流形式" style="width: 300px">
            <el-option
                v-for="dict in pc_streaming"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="记录设置" prop="pcRecording">
          <el-select v-model="form.pcRecording" placeholder="请选择记录设置" style="width: 300px">
            <el-option
                v-for="dict in pc_recording"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="充电模式" prop="pcCharging">
          <el-select v-model="form.pcCharging" placeholder="请选择充电模式" style="width: 300px">
            <el-option
                v-for="dict in pc_charging"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <!-- 地理位置部分 -->
    <div>
      <h3>地理位置</h3>
      <el-form :model="form" style="margin-top: 10px; margin-left: 20px;">
        <el-form-item label="高度校准" >
          <el-row :gutter="10">
            <el-col :span="200">
              <el-input-number
                  v-model="form.pcHeight"
                  :min="0"
                  :max="1000"
                  :step="1"
                  placeholder="请输入高度"
                  size="default"
              />
            </el-col>
            <el-col :span="2">
              <span>m</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="默认地图" prop="pcMap">
          <el-select v-model="form.pcMap" placeholder="请选择默认地图" style="width: 300px">
            <el-option
                v-for="dict in pc_map"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="坐标格式" prop="pcFormat">
          <el-select v-model="form.pcFormat" placeholder="请选择坐标格式" style="width: 300px" @change="handleFormatChange">
            <el-option
                v-for="dict in pc_format"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="中心坐标">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input v-model="form.pcLongitude" placeholder="请输入经度"></el-input>
            </el-col>
            <el-col :span="12">
              <el-input v-model="form.pcLatitude" placeholder="请输入纬度"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="默认图层">
          <el-row :gutter="10">
            <el-col :span="200">
              <el-input-number
                  v-model="form.pcLayer"
                  :min="form.pcMin"
                  :max="form.pcMax"
                  :step="1"
                  placeholder="请输入默认图层"
                  style="width: 250px"
              />
            </el-col>
            <el-col :span="2">
              <span>层</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="最小图层">
          <el-row :gutter="10">
            <el-col :span="200">
              <el-input-number
                  v-model="form.pcMin"
                  :min="0"
                  :max="form.pcMax"
                  :step="1"
                  placeholder="请输入最小图层"
                  style="width: 250px"
              />
            </el-col>
            <el-col :span="2">
              <span>层</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="最大图层">
          <el-row :gutter="10">
            <el-col :span="200">
              <el-input-number
                  v-model="form.pcMax"
                  :min="form.pcMin"
                  :max="100"
                  :step="1"
                  placeholder="请输入最大图层"
                  style="width: 250px"
              />
            </el-col>
            <el-col :span="2">
              <span>层</span>
            </el-col>
          </el-row>
        </el-form-item>
        <!-- 添加地图组件 -->
        <div class="map-container">
          <MapComponent
                        ref="mapRef"
                        :mapConfig="mapConfig"
                        :showtoolbox="isShow"
                        :showswitchbox="isShow"
                        :showbottomBox="isShow"
                        :showweather="isShow"
                        :showDistanceLegend="isShow"/>
        </div>
      </el-form>
    </div>
    <div style="text-align: center; margin-top: 20px;">
      <el-button type="primary" @click="submitForm" >保存</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { ref, getCurrentInstance, watch, computed } from 'vue';
import { listPcCustomized, updatePcCustomized } from '@/api/customized/pc';
import { useDict } from "@/utils/dict.js";
import MapComponent from '@/components/MapComponent/index.vue';
const mapRef = ref(null);
const isShow = ref(false)

const { proxy } = getCurrentInstance();

// 使用若依字典
const { pc_streaming, pc_recording, pc_charging, pc_map, pc_format } = useDict(
    'pc_streaming',
    'pc_recording',
    'pc_charging',
    'pc_map',
    'pc_format'
);
const form = ref({
  id: null,
  pcIcon: '',
  pcSystem: '',
  pcPassword: '',
  pcStreaming: '',
  pcRecording: '',
  pcCharging: '',
  pcHeight: 0,
  pcMap: '',
  pcFormat: '',
  pcLongitude: 0,
  pcLatitude: 0,
  originalPcLongitude: 0, // 保存原始的十进制经度
  originalPcLatitude: 0,  // 保存原始的十进制纬度
  pcLayer: 0,
  pcMin: 0,
  pcMax: 0,
  isDecimalFormat: true // 添加一个标志来记录当前的坐标格式，默认是十进制
});

// 确保默认图层在最大和最小图层之间
watch([() => form.value.pcMin, () => form.value.pcMax, () => form.value.pcLayer], ([newMin, newMax, newLayer]) => {
  if (newLayer < newMin) {
    form.value.pcLayer = newMin;
  } else if (newLayer > newMax) {
    form.value.pcLayer = newMax;
  }
  if (newMin > newMax) {
    form.value.pcMax = newMin;
  }
});

// 十进制转度分秒的函数
const decimalToDMS = (decimal) => {
  const degrees = Math.floor(decimal);
  const minutes = Math.floor((decimal - degrees) * 60);
  const seconds = ((decimal - degrees) * 60 - minutes) * 60;
  return `${degrees}°${minutes}'${seconds.toFixed(2)}"`;
};

// 度分秒转十进制的函数
const DMSToDecimal = (dms) => {
  if (typeof dms === 'string') {
    const parts = dms.match(/(\d+)°(\d+)'([\d.]+)"/);
    if (parts) {
      const degrees = parseInt(parts[1], 10);
      const minutes = parseInt(parts[2], 10);
      const seconds = parseFloat(parts[3]);
      return degrees + (minutes / 60) + (seconds / 3600);
    }
  }
  return parseFloat(dms); // 如果不是度分秒格式，尝试直接转换为数字
};

// 处理坐标格式变化的函数
const handleFormatChange = () => {
  if (form.value.pcFormat === '2') {
    form.value.pcLongitude = decimalToDMS(Number(form.value.pcLongitude));
    form.value.pcLatitude = decimalToDMS(Number(form.value.pcLatitude));
    form.value.isDecimalFormat = false;
  } else {
    form.value.pcLongitude = form.value.originalPcLongitude;
    form.value.pcLatitude = form.value.originalPcLatitude;
    form.value.isDecimalFormat = true;
  }
};

// 提交表单方法
const submitForm = async () => {
  // 解构赋值排除 pcFormat 字段
  let { pcFormat, ...submitData } = { ...form.value };
  if (!form.value.isDecimalFormat) {
    submitData.pcLongitude = DMSToDecimal(form.value.pcLongitude);
    submitData.pcLatitude = DMSToDecimal(form.value.pcLatitude);
  }
  if (form.value.id != null) {
    const res = await updatePcCustomized(submitData);
    if (res.code === 200) {
      proxy.$modal.msgSuccess("保存成功");
    } else {
      proxy.$modal.msgError("保存失败");
    }
  }
};

const List = async () => {
  const res = await listPcCustomized({});
  if (res.code === 200) {
    console.log('查询成功', res.rows);
    mapRef.value.drawLocationMarker(res.rows[0].pcLongitude, res.rows[0].pcLatitude);
    form.value = res.rows[0];
    form.value.originalPcLongitude = form.value.pcLongitude; // 初始化时保存原始值
    form.value.originalPcLatitude = form.value.pcLatitude;
  }
};
List();

// 计算属性，根据当前格式返回十进制经度
const getDecimalLongitude = computed(() => {
  return DMSToDecimal(form.value.pcLongitude);
});

// 计算属性，根据当前格式返回十进制纬度
const getDecimalLatitude = computed(() => {
  return DMSToDecimal(form.value.pcLatitude);
});

// 封装地图配置对象
const mapConfig = computed(() => ({
  pcLongitude: getDecimalLongitude.value,
  pcLatitude: getDecimalLatitude.value,
  pcLayer: form.value.pcLayer
}));

// 监听经纬度变化，调用 drawLocationMarker 方法
watch([() => form.value.pcLongitude, () => form.value.pcLatitude], ([newLongitude, newLatitude]) => {
  if (mapRef.value) {
    const decimalLongitude = DMSToDecimal(newLongitude);
    const decimalLatitude = DMSToDecimal(newLatitude);
    mapRef.value.drawLocationMarker(decimalLongitude, decimalLatitude);
  }
}, { deep: true });
</script>

<style scoped lang="scss">
.box-card {
  padding: 20px;
}

.upload-demo {
  margin-bottom: 10px;
}

.upload-avatar {
  width: 100px;
  height: 100px;
  overflow: hidden;
  margin-top: 10px;
  border-radius: 50%;

  img {
    width: 100%;
    height: 100%;
  }
}

.map-container {
  height: 300px; // 设置地图容器的高度
  width: 600px; //  设置地图容器的宽度
  position: relative;
}

#cesiumContainer {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
</style>
